package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ProductApiService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 赵勇镔
 * @Time: 2021/5/17 11:10
 * @Description:
 */
@Service
public class ProductApiServiceImpl implements ProductApiService {


    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired//解决分布式相关问题
    private RedissonClient redissonClient;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;


    //根据skuId 获取SkuInfo信息
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //设置查询K值
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //先在缓存库中查询,如果没有
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (skuInfo == null) {
            //先上锁 去Db中查询
            //锁id
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //过期不候锁 JUC 参数 获取锁的时间 锁的过期时间 时间单位
            try {
                boolean tryLock = lock.tryLock(1, 1, TimeUnit.SECONDS);
                if (tryLock) {//获取到锁
                    //查询Db
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (skuInfo != null) {//Db中查到了
                        //查询图片属性添加到skuInfo中
                        skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
                        //添加到缓存库中 k值 对象 过期时间 时间单位
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300)
                                , TimeUnit.SECONDS);

                    } else {//Db中没查到
                        //防止击穿问题 缓存空结果
                        skuInfo = new SkuInfo();
                        //参数 缓存k 缓存对象 缓存时间 缓存单位 加随机秒数 防止雪崩
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                60 * 5 + new Random().nextInt(100), TimeUnit.SECONDS);
                    }
                    //执行完最后解锁
                    lock.unlock();

                } else {//未获取到锁
                    //休息两秒
                    TimeUnit.SECONDS.sleep(2);
                    //再重新获取
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //缓存库中有直接返回
        return skuInfo;
    }

    /*//根据skuId 获取SkuInfo信息
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key值
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId +
                RedisConst.SKUKEY_SUFFIX;
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if(null == skuInfo){
            //分布式锁的Key值
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //解决缓存击穿问题   上分布式锁
            //UUID 36长度 去掉四个小横线  32位长度
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid
                    ,1,TimeUnit.SECONDS);
            if(lock){
                //获取到了锁
                //2:没有 查询DB
                skuInfo = skuInfoMapper.selectById(skuId);
                if(null != skuInfo){
                    skuInfo.setSkuImageList(skuImageMapper.
                            selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
                    //再保存缓存一份
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),//缓存雪崩
                            TimeUnit.SECONDS);
                }else{
                    // 缓存穿透   空结果  应付攻击者  DB
                    skuInfo = new SkuInfo();
                    //再保存缓存一份
                    redisTemplate.opsForValue().set(cacheKey,
                            skuInfo,5,
                            TimeUnit.MINUTES);
                }
                //删除了
                //判断是否是自己的锁
         *//*       Object u = redisTemplate.opsForValue().get(cacheLockKey);
                if(uuid.equals(u)){
                    //是自己的锁
                    redisTemplate.delete(cacheLockKey);
                }*//*
                //LUA脚本   Nginx或redis  C语言开发软件  LUA脚本 C语言开发的
                //删除具备原子性操作
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
            }else{
                //未获取到锁
                try {
                    TimeUnit.SECONDS.sleep(2);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //3:统一返回
        return skuInfo;
    }*/

    /*注意金额这种数据不能使用缓存*/
    @Override
    @GmallCache(prefix = "baseCategoryView:")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    @GmallCache(prefix = "getSpuSaleAttrValueChecked:")
    public List<SpuSaleAttr> getSpuSaleAttrValueChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrValueChecked(skuId, spuId);
    }

    @Override
    @GmallCache(prefix = "getValuesSkuJson")
    public Map getValuesSkuJson(Long spuId) {
        Map result = new HashMap();
        List<Map> listMap = skuSaleAttrValueMapper.getValuesSkuJson(spuId);
        listMap.forEach(map -> {
            result.put(map.get("valueIds"), map.get("sku_id"));
        });
        return result;
    }

    @Override
    public BigDecimal getPrice(Long spuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(spuId);
        if (skuInfo != null) {
            return skuInfo.getPrice();
        } else {
            return null;
        }

    }

    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long id) {
        return baseTrademarkMapper.selectById(id);
    }

    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }


}
